using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace lwzlz.Application.System
{
    public class OrderDetailService
    {
        private readonly IRepository<OrderDetail> _repository;

        public OrderDetailService()
        {
            _repository = new Repository<OrderDetail>();
        }

        #region 查询

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OrderDetail Get(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="dic_conditions"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<OrderDetailOutput> GetListPage(
            int pageNumber, int rowsPerPage, Dictionary<string, string> dic_conditions, string field, string order, out int count)
        {
            #region 参数查询

            string where = " WHERE 0=0 ";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();

            //订单Id
            if (dic_conditions.ContainsKey("OrderId"))
            {
                dic.Add("@OrderId", dic_conditions["OrderId"]);
                where += " AND OrderId=@OrderId ";
            }
            //商品Id
            if (dic_conditions.ContainsKey("CommodityId"))
            {
                dic.Add("@CommodityId", dic_conditions["CommodityId"]);
                where += " AND CommodityId=@CommodityId ";
            }
            //商品名称
            if (dic_conditions.ContainsKey("CommodityName"))
            {
                dic.Add("@CommodityName", dic_conditions["CommodityName"]);
                where += " AND CommodityName=@CommodityName ";
            }
            //商品编号
            if (dic_conditions.ContainsKey("CommodityCode"))
            {
                dic.Add("@CommodityCode", dic_conditions["CommodityCode"]);
                where += " AND CommodityCode=@CommodityCode ";
            }
            //分类Id
            if (dic_conditions.ContainsKey("CategoryId"))
            {
                dic.Add("@CategoryId", dic_conditions["CategoryId"]);
                where += " AND CategoryId=@CategoryId ";
            }
            //分类名称
            if (dic_conditions.ContainsKey("CategoryName"))
            {
                dic.Add("@CategoryName", dic_conditions["CategoryName"]);
                where += " AND CategoryName=@CategoryName ";
            }
            //商品图片
            if (dic_conditions.ContainsKey("CommodityPic"))
            {
                dic.Add("@CommodityPic", dic_conditions["CommodityPic"]);
                where += " AND CommodityPic=@CommodityPic ";
            }
            //商品介绍
            if (dic_conditions.ContainsKey("CommodityIntroduce"))
            {
                dic.Add("@CommodityIntroduce", dic_conditions["CommodityIntroduce"]);
                where += " AND CommodityIntroduce=@CommodityIntroduce ";
            }
            //商品金额
            if (dic_conditions.ContainsKey("CommodityMoney"))
            {
                dic.Add("@CommodityMoney", dic_conditions["CommodityMoney"]);
                where += " AND CommodityMoney=@CommodityMoney ";
            }
            //购买数量
            if (dic_conditions.ContainsKey("Number"))
            {
                dic.Add("@Number", dic_conditions["Number"]);
                where += " AND Number=@Number ";
            }
            //合计金额
            if (dic_conditions.ContainsKey("TotalMoney"))
            {
                dic.Add("@TotalMoney", dic_conditions["TotalMoney"]);
                where += " AND TotalMoney=@TotalMoney ";
            }

            #endregion

            #region 排序

            //排序sql语句拼接
            string orderby = " Id DESC ";//默认排序
            if (!string.IsNullOrWhiteSpace(field))
            {
                orderby = string.Format("{0} {1}", field, string.IsNullOrWhiteSpace(order) ? "DESC" : order);
            }

            #endregion

            var list = _repository.GetListPaged(pageNumber, rowsPerPage, where, orderby, dic);

            count = GetListCount(where, dic);

            return Mapper.Map<List<OrderDetailOutput>>(list);
        }

        /// <summary>
        /// 获取查询结果行数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetListCount(string conditions, object param)
        {
            return _repository.RecordCount(conditions, param);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public List<OrderDetailOutput> GetList(int orderId)
        {
            var sql = @"
                SELECT *
                FROM dbo.Ser_OrderDetail
                WHERE IsDeleted = 0";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();
            //分类Id
            dic.Add("@OrderId", orderId);
            sql += " AND OrderId = @OrderId";

            var list = _repository.Query<OrderDetailOutput>(sql, dic).ToList();
            return list;
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int? Insert(OrderDetail entity, IDbTransaction dbtran)
        {
            return _repository.Insert(entity, dbtran);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(OrderDetailInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = Mapper.Map<OrderDetail>(model);
                entity.CreatorUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.CreationTime = DateTime.Now;

                int? Id = _repository.Insert(entity, dbtran);

                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Edit(OrderDetailInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                DateTime now = DateTime.Now;

                var entity = _repository.Get(model.Id, dbtran);
                Mapper.Map(model, entity);//把model数据转移到entity
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.LastModificationTime = DateTime.Now;

                _repository.Update(entity, dbtran);
                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    OrderDetail model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        #endregion
    }
}

